package xyz.lisys.utils;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateEditor extends PropertyEditorSupport {
    private String formatter = "yyyy-MM-dd";

    public DateEditor() {
    }

    public DateEditor(String formatter) {
        this.formatter = formatter;
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        SimpleDateFormat dateFormat = new SimpleDateFormat(formatter);
        Date date;
        try {
            date = dateFormat.parse(text);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        setValue(date);
    }

    @Override
    public String getAsText() {
        Date date = (Date) getValue();
        SimpleDateFormat dateFormat = new SimpleDateFormat(formatter);
        return dateFormat.format(date);
    }
}
